<?php

namespace support\middleware;

use app\common\Sign;
use support\bootstrap\Container;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class AppUserBaseControl implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {
        $access_token = $request->header('authorization');
        if (!isset($access_token)) {
            return error('401', 'access_token is null');
        } else {
            $request->access_token = $access_token;
            $payload = Sign::decode($access_token,config('app.jwt_sign'));
            if($payload){
                $request->user_id = $payload['uid'];
                if ($request->controller) {
                    // 禁止直接访问beforeAction afterAction
                    if ($request->action === 'beforeAction' || $request->action === 'afterAction') {
                        return response('<h1>404 Not Found</h1>', 404);
                    }
                    $controller = Container::get($request->controller);
                    if (method_exists($controller, 'beforeAction')) {
                        $before_response = call_user_func([$controller, 'beforeAction'], $request);
                        if ($before_response instanceof Response) {
                            return $before_response;
                        }
                    }
                }

            }
            else{
                return error('401', 'access_token is invalid');
            }
            $response = $next($request);
        }
        return $response;
    }
}